<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/26
 * Time: 11:24
 */

namespace Admin\Controller;

use Think\Upload;

class BrandController extends CommenController
{

	public function index(){
		$brand = M('brand')->order('sort')->select();//分配变量
		$this->assign('brand',$brand);
		$this->display();
	}
	/**
	 * 添加品牌
	 */
	public function add(){
		if (IS_POST){
			$_POST['ishot'] = isset($_POST['ishot']) ? 1 : 0;
			$url = $this->upload();
//			$this->p($url);die;
			$_POST['logo'] = $url;
			if(M('brand')->add($_POST)){
				$this->success('添加品牌成功', U('index'));
				die;
			}else{
				$this->error('添加品牌失败');
				die;
			}
		}
		$this->display();
	}
	/**
	 * 品牌LOGO图上传
	 *
	 */
	public function upload(){
		$upload = new Upload();// 实例化上传类
		$upload->maxSize   =     3145728 ;// 设置附件上传大小
		$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		$upload->rootPath  =     './'; // 设置附件上传根目录
		$upload->savePath  =     'Uploads/Logo/'; // 设置附件上传（子）目录
		// 上传文件
		$info   =   $upload->upload();
		$url=$info['logo']['savepath'].$info['logo']['savename'];
		return $url;
	}
	/**
	 * 编辑品牌
	 */
	public function edit(){
		$bid = I('get.bid');
//		$this->p($bid);
        //获取及分配旧数据
		$oldData = M('brand')->find($bid);
//		$this->p($oldData);
		$this->assign('oldData',$oldData);

		if(IS_POST){
			$url = $this->upload();
			$_POST['logo'] = $url;
			$_POST['ishot'] = isset($_POST['ishot']) ? 1 : 0;
			if (!$_POST['logo']){//当未重新上传logo时 调用原logo
				$_POST['logo'] = $oldData['logo'];
			}
//			$this->p($_POST);
			if(M('brand')->where(['bid'=>$bid])){
				$data =$_POST;
//				$this->p($data);die;
				M('brand')->save($data);
				$this->success('修改成功', U('index'));
				die;
			}else{
				$this->error('修改失败');
				die;
			}
		}

		//加载模板
		$this->display();

	}
	/**
	 * 删除品牌
	 */
	public function del(){
		$bid = I('get.bid');
//		$this->p($bid);
		if(M('brand')->delete($bid)){
			$this->success('删除品牌成功');
			die;
		}else{
			$this->error('删除品牌失败');
			die;
		}

	}

}